var _upload = {
	SWFUpload: null,
	queuedFiles: [],
	successNum: 0,
	stopped: false,
	setting: {
		preview_url: '/img/',
		form_name: 'form',
		upload_type: 'image',
		upload_sid: '',
		upload_flash_url: '/swfupload.swf',
		upload_post_url: '/upload'
	},
	swfu: {
		file_post_name: 'file',
		flash_url: 'swfupload.swf',
		upload_url: 'upload',
		post_params: {},
		file_size_limit : "8 MB",
		file_types : "*.jpg;*.png",
		file_types_description : "Web Image Files",
		file_upload_limit : 0,
		file_queue_limit : 50,
		custom_settings : {},
		http_success : [201, 202],
		debug: false,
		// button_image_url: "images/TestImageNoText_65x29.png",
		button_width: "300",
		button_height: "29",
		button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES,
		button_placeholder_id: "spanButtonPlaceHolder",
		button_text: '<span class="theFont">CLICK HERE TO SELECT IMAGES ..</span>',
		button_text_style: ".theFont{font-size:16;text-decoration:underline;color:#0000FF;}",
		button_cursor: SWFUpload.CURSOR.HAND,
		button_text_left_padding: 12,
		button_text_top_padding: 3,
		swfupload_loaded_handler: function() {
	
		},
		file_dialog_complete_handler: function(numFilesSelected, numFilesQueued, totalNumOfFile) {
			if(_upload.swfu.file_queue_limit > 0 && numFilesSelected > _upload.swfu.file_queue_limit) {
				alert('Too many files selected.\n\nLIMIT: ' + _upload.swfu.upload_queue_limit + '\nSELECTED:' + numFilesSelected);
				return;
			}
			$('#queued-number').html(_upload.queuedFiles.length);
			_upload.showUploadButton();
		},
		file_queued_handler: function(file) {
			var id = file['name'] + file['size'].toString();
			if(_upload.isInQueuedList(file)) return;
			file['key'] = id;
			_upload.queuedFiles.push(file);
			_upload.addQueuedLine(file);
		},
		file_queue_error_handler: function(file, code, msg) {
			_upload.addQueuedLine(file, msg);
		},
		queue_complete_handler: function(numFilesUploaded) {
			alert('uploaded num: ' + numFilesUploaded);
		},
		upload_start_handler: function(file) {
			_upload.swfu.upload_progress_handler(file, 0, file['size']);
		},
		upload_progress_handler: function(file, bytes, total) {
			_upload.addUploadLine(file, bytes, total);
		},
		upload_success_handler : function(file, data, response) {
			try {
				var json = JSON.parse(data);
				if(json.status == false || json.status == 0) {
					throw json.message;
				}
				if(typeof(json.file) != 'undefined' && typeof(json.file.hash) != 'undefined') {
					var s = '', i = _upload.setting.preview_url + json.file.hash;
					s += '<div class="previewList">';
					if(typeof(json.file.id) != 'undefined') {
						s += '<input type="hidden" name="photo_id[]" value="' + json.file.id + '" />';
					}
					s += '<a href="' + i + '/large" target="_blank"><span><img src="' + i + '/thumb" /></span></a>';
					s += '<div class="clear"></div>';
					s += '<p>' + json.file.name + '</p>';
					s += '</div>';
					$('#preview').append(s);
				}
				var s = '<td colspan="2" class="green">Complete: ' + file['name'] + '</td><td class="right">' + file['size'] + '</td><td></td>';
				$('#tr-' + file['id']).html(s);
				_upload.successNum++;
			} catch (e) {
				var msg = typeof(e) == 'string' ? e : e.message;
				$('#tr-' + file['id']).html('<td colspan="4"><em class="red">' + msg + '</em></td>');
			}
			//_upload.removeQueuedFile(file);
		},
		upload_error_handler : function(file, code, msg) {
			_upload.addUploadLine(file, 0, file['size'], msg + '[code:' + code + ']');
			_upload.removeQueuedFile(file);
		},
		upload_complete_handler : function(file) {
			//_upload.removeQueuedFile(file);
			_upload.doUpload(false);
		}
	},
	initialize: function() {
		this.swfu.flash_url = this.setting.upload_flash_url;
		this.swfu.upload_url = this.setting.upload_post_url;
		this.SWFUpload = new SWFUpload(this.swfu);
	},
	addQueuedLine: function(file, msg) {
		var s = '';
		s += '<tr id="tr-' + file['id'] + '">';
		if(msg) {
			s += '<td colspan="4">'+ file['name'] + ': <em class="red">' + msg + '</em></td>';
		} else {
			s += '<td><input type="checkbox" name="SWFFileId[' + file['id'] + ']" value="' + file['id'] + '" id="' + file['id'] + '" checked="checked" /></td>';
			s += '<td><label for="' + file['id'] + '" class="for-checkbox">' + file['name'] + '</label></td>';
			s += '<td class="right">' + file['size'] + '</td>';
			s += '<td></td>';
		}
		s += '</tr>';
		$('#file-queued').append(s);
	},
	addUploadLine: function(file, bytes, total, msg) {
		var s = '';
		if(msg) {
			s += '<td colspan="2"><em class="red">' + msg + '</em></td>';
		} else {
			var percent = (bytes / total) * 100;
			if(percent >= 100) {
				s += '<td colspan="2"><em class="green">PROCESSING...</em></td>';
			} else {
				s += '<td colspan="2">' + file['name'] + '(<em class="red">' + percent + '%</em>)</td>';
			}
		}
		s += '<td class="right">' + total + '</td>';
		s += '<td></td>';
		$('#tr-' + file['id']).html(s);
	},
	removeQueuedFile: function(file) {
		var id = file['name'] + file['size'].toString();
		var index = key = 0;
		for(var i = 0; i < this.queuedFiles.length; i++) {
			if(this.queuedFiles[i]['key'] == id) {
				index = key;
				break;
			}
			key++;
		}
		this.queuedFiles.splice(index, 1);
	},
	isInQueuedList: function(file) {
		var id = file['name'] + file['size'].toString();
		for(var i = 0; i < this.queuedFiles.length; i++) {
			if(this.queuedFiles[i]['key'] == id) {
				return true;
			}
		}
		return false;
	},
	setParamData: function() {
		this.SWFUpload.addPostParam('type', this.setting.upload_type);
		this.SWFUpload.addPostParam('sid', this.setting.upload_sid);
		var serializeData = $('form#' + this.setting.form_name).serializeArray();
		var data = [];
		for(var i in serializeData) {
			this.SWFUpload.addPostParam(serializeData[i]['name'], encodeURIComponent(serializeData[i]['value']));
			data.push(serializeData[i]['name'] + '=' + encodeURIComponent(serializeData[i]['value']));
		}
		return data;
	},
	showUploadButton: function() {
		if(this.queuedFiles.length > 0) {
			$('#spanButtonUpload').show();
		}
		this.hideStopButton();
		this.hideNextButton();
	},
	showStopButton: function() {
		$('#spanButtonStop').show();
		this.hideUploadButton();
		this.hideNextButton();
	},
	showNextButton: function() {
		$('#spanButtonNextStep').show();
		this.hideUploadButton();
		this.hideStopButton();
	},
	hideUploadButton: function() {
		$('#spanButtonUpload').hide();
	},
	hideStopButton: function() {
		$('#spanButtonStop').hide();
	},
	hideNextButton: function() {
		if(_upload.successNum > 0 && _upload.stopped == true) {
			$('#spanButtonNextStep').show();
		} else {
			$('#spanButtonNextStep').hide();			
		}
	},
	doUpload: function(force) {
		if(force == null || typeof(force) == 'undefined') force = true;
		if(this.stopped && force == false) return;
		this.stopped = false;
		this.showStopButton();
		var c = $('#file-queued').find('input[type=checkbox]:checked');
		if(c.length <= 0) {
			this.doComplete();
			return;
		}
		if(force == true) {
			this.SWFUpload.setPostParams({});
			this.setParamData();
		}
		this.SWFUpload.startUpload(c.eq(0).attr('value'));
	},
	doStop: function() {
		this.stopped = true;
		this.SWFUpload.stopUpload();
		this.showUploadButton();
	},
	doComplete: function() {
		this.showNextButton();
	}
};

